default: all

XLEN ?= 32

RISCV_PREFIX ?= /home/ushio/riscv/bin/riscv$(XLEN)-unknown-elf-

RISCV_GCC ?= $(RISCV_PREFIX)gcc

COMMON_FLAGS  := -fno-pic -march=rv32i -mabi=ilp32 -Ofast
CFLAGS   := -Ofast -MMD -Wall -ggdb -I./include \
            -fno-asynchronous-unwind-tables -fno-builtin -fno-stack-protector \
            -Wno-main $(COMMON_FLAGS) -static -fdata-sections -ffunction-sections \
			-mcmodel=medany
ASFLAGS  := -MMD -I./include $(COMMON_FLAGS) -Ofast
LDFLAGS  := -Tsections.ld -nostartfiles -nostdlib -static -L. -lcoremark

RISCV_OBJDUMP ?= $(RISCV_PREFIX)objdump --disassemble-all --disassemble-zeroes --section=.text --section=.text.startup --section=.text.init --section=.data

RISCV_OBJCOPY ?= $(RISCV_PREFIX)objcopy -O verilog

RISCV_HEXGEN ?= 'BEGIN{output=0;}{ gsub("\r","",$$(NF)); if ($$1 ~/@/) {if ($$1 ~/@00000000/) {output=code;} else {output=1- code;}; gsub("@","0x",$$1); addr=strtonum($$1); if (output==1) {printf "@%08x\n",(addr%262144)/4;}} else {if (output==1) { for(i=1;i<NF;i+=4) print $$(i+3)$$(i+2)$$(i+1)$$i;}}}'

RISCV_MIFGEN ?= 'BEGIN{printf "WIDTH=32;\nDEPTH=%d;\n\nADDRESS_RADIX=HEX;\nDATA_RADIX=HEX;\n\nCONTENT BEGIN\n",depth ; addr=0;} {gsub("\r","",$$(NF)); if ($$1 ~/@/) { sub("@","0x",$$1);addr=strtonum($$1);} else {printf "%04X : %s;\n", addr, $$1;addr=addr+1;}} END{print "END\n";}'

SFILES := $(shell find . -name "*.S")
CFILES := $(shell find . -name "*.c")

DST_DIR := build

SOBJS := $(addprefix $(DST_DIR)/, $(addsuffix .o, $(basename $(SFILES))))
COBJS := $(addprefix $(DST_DIR)/, $(addsuffix .o, $(basename $(CFILES))))

SDFILES := $(addprefix $(DST_DIR)/, $(addsuffix .d, $(basename $(SFILES))))
CDFILES := $(addprefix $(DST_DIR)/, $(addsuffix .d, $(basename $(CFILES))))

EXEC := $(DST_DIR)/main

CORE : core_list_join.c core_main.c core_matrix.c core_portme.c core_state.c core_util.c ee_printf.c
	@$(RISCV_GCC) -Ofast -c core_list_join.c core_main.c core_matrix.c core_portme.c core_state.c core_util.c ee_printf.c

$(DST_DIR)/%.o: %.c
	@echo + CC $<
	@mkdir -p $(dir $@)
	@$(RISCV_GCC) -c $(CFLAGS) $< -o $@

$(DST_DIR)/%.o: %.S
	@echo + AS $<
	@mkdir -p $(dir $@)
	@$(RISCV_GCC) -c $(ASFLAGS) $< -o $@

$(EXEC).elf : CORE $(SOBJS) $(COBJS)
	@echo + LD $@
	@$(RISCV_GCC) $(LDFLAGS) $(SOBJS) $(COBJS) rt.a -o $@
	@$(RISCV_OBJDUMP) $(EXEC).elf > $(EXEC).dump

$(EXEC).img: $(EXEC).elf
	@echo + GENERATE IMG
	@$(RISCV_OBJCOPY) $< $@

$(EXEC).hex: $(EXEC).img
	@echo + GENERATE HEX
	@awk -v code=1 $(RISCV_HEXGEN) $< > $@
	@awk -v code=0 $(RISCV_HEXGEN) $< > $(EXEC)_d.hex

$(EXEC).mif: $(EXEC).hex
	@echo + GENERATE MIF
	@awk -v depth=32768 $(RISCV_MIFGEN) $< > $@
	@awk -v depth=32768 $(RISCV_MIFGEN) $(EXEC)_d.hex > $(EXEC)_d.mif

.PHONY: all clean

all: $(EXEC).mif

clean:
	@echo + CLEAN
	@rm -f $(EXEC) $(SOBJS) $(COBJS) $(SDFILES) $(CDFILES) $(EXEC).elf $(EXEC).dump $(EXEC).img $(EXEC).hex $(EXEC)_d.hex $(EXEC).mif $(EXEC)_d.mif
